using System;
using System.Web.Routing;
using ManagedUIFlow.Infrastructure.Services;
using ManagedUIFlow.Model;

namespace ManagedUIFlow.Infrastructure.Commands
{
    public class EndFlow : ICommand
    {
        private FlowViewServiceBuilder _flowSerializerBuilder;
        private readonly RequestContext _requestContext;
        private ApplicationController _appController;

        public EndFlow(RequestContext requestContext)
        {
            _requestContext = requestContext;
        }

        public FlowViewServiceBuilder FlowSerializerBuilder
        {
            get
            {
                return _flowSerializerBuilder ?? FlowViewServiceBuilder.Current;
            }
            set { _flowSerializerBuilder = value; }
        }

        public ApplicationController ApplicationController
        {
            get
            {
                return _appController ?? ApplicationController.Current;
            }
            set
            {
                _appController = value;
            }
        }

        public void Execute(ManagedFlow flow)
        {
            if (string.IsNullOrEmpty(flow.CurrentNavigation))
            {
                var mainFlowKey = flow.Key.ToString().Split('_');
                var flowSerializer = FlowSerializerBuilder.GetFlowViewService();
                flowSerializer.Remove(flow, _requestContext);
                if (mainFlowKey.Length > 1)
                {
                    flow = flowSerializer.Deserialize(mainFlowKey[0], _requestContext);

                    if (flow == null)
                        throw new FlowException("Couldn't restore main flow.");
                }
                else
                    return;
            }

            ApplicationController.Execute(_requestContext, flow);
        }
    }
}